const express = require('express');
const http = require('http');
const socketIo = require('socket.io');
const path = require('path');
const cors = require('cors');
const multer = require('multer');
const session = require('express-session');
const cookieParser = require('cookie-parser');
const db = require('./db');

// 初始化数据库
db.initDb();

// 创建 Express 应用
const app = express();
const server = http.createServer(app);
const io = socketIo(server, {
  cors: {
    origin: "*",
    methods: ["GET", "POST"]
  }
});

// 中间件配置
app.use(cors());
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use(cookieParser());
app.use(session({
  secret: 'bbs_web_secret_key',
  resave: false,
  saveUninitialized: true,
  cookie: { secure: false }
}));

// 设置静态文件目录
app.use(express.static(path.join(__dirname, '../public')));

// 配置文件上传
const storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, path.join(__dirname, '../uploads'));
  },
  filename: function (req, file, cb) {
    const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1E9);
    cb(null, uniqueSuffix + '-' + file.originalname);
  }
});

const upload = multer({ storage: storage });

// 导入路由
const authRoutes = require('./routes/auth');
const postRoutes = require('./routes/posts');
const fileRoutes = require('./routes/files');

// 使用路由
app.use('/api/auth', authRoutes);
app.use('/api/posts', postRoutes);
app.use('/api/files', fileRoutes);

// 房间管理API
app.post('/api/rooms', async (req, res) => {
  if (!req.session.userId) {
    return res.status(401).json({ error: '请先登录' });
  }

  const { name, description, password, isPrivate } = req.body;

  if (!name || !name.trim()) {
    return res.status(400).json({ error: '房间名称不能为空' });
  }

  try {
    const roomId = Date.now().toString(); // 生成唯一的房间ID

    const result = await db.createRoom({
      id: roomId,
      name: name.trim(),
      description: description || '',
      password: password || null,
      is_private: isPrivate || false,
      creator_id: req.session.userId
    });

    res.json({
      id: result.id,
      name: result.name,
      description: result.description,
      isPrivate: isPrivate || false,
      createdAt: new Date().toISOString()
    });
  } catch (error) {
    console.error('创建房间失败:', error);
    res.status(500).json({ error: '创建房间失败' });
  }
});

// 获取所有房间
app.get('/api/rooms', async (req, res) => {
  try {
    const userId = req.session.userId || null;
    const rooms = await db.getRooms(userId);
    const roomsList = rooms.map(room => ({
      id: room.id,
      name: room.name,
      description: room.description || '',
      isPrivate: room.is_private,
      createdAt: room.created_at,
      creator_id: room.creator_id
    }));

    res.json(roomsList);
  } catch (error) {
    console.error('获取房间列表失败:', error);
    res.status(500).json({ error: '获取房间列表失败' });
  }
});

// 加入房间
app.post('/api/rooms/:id/join', async (req, res) => {
  if (!req.session.userId) {
    return res.status(401).json({ error: '请先登录' });
  }

  const { password } = req.body;
  const roomId = req.params.id;

  try {
    await db.joinRoom(roomId, req.session.userId, password);
    res.json({ success: true });
  } catch (error) {
    console.error('加入房间失败:', error);
    res.status(400).json({ error: error.message });
  }
});

// 离开房间
app.post('/api/rooms/:id/leave', async (req, res) => {
  if (!req.session.userId) {
    return res.status(401).json({ error: '请先登录' });
  }

  const roomId = req.params.id;

  try {
    await db.leaveRoom(roomId, req.session.userId);
    res.json({ success: true });
  } catch (error) {
    console.error('离开房间失败:', error);
    res.status(400).json({ error: error.message });
  }
});

// 删除房间
app.delete('/api/rooms/:id', async (req, res) => {
  if (!req.session.userId) {
    return res.status(401).json({ error: '请先登录' });
  }

  const roomId = req.params.id;

  try {
    await db.deleteRoom(roomId, req.session.userId);
    res.json({ success: true });
  } catch (error) {
    console.error('删除房间失败:', error);
    res.status(400).json({ error: error.message });
  }
});

// 获取房间成员
app.get('/api/rooms/:id/members', async (req, res) => {
  if (!req.session.userId) {
    return res.status(401).json({ error: '请先登录' });
  }

  const roomId = req.params.id;

  try {
    const members = await db.getRoomMembers(roomId);
    res.json(members);
  } catch (error) {
    console.error('获取房间成员失败:', error);
    res.status(500).json({ error: '获取房间成员失败' });
  }
});

// 基本路由
app.get('/', (req, res) => {
  res.sendFile(path.join(__dirname, '../public/index.html'));
});

// 聊天室功能
const users = {};
const rooms = {
  'public': {
    id: 'public',
    name: '公共聊天室',
    description: '所有用户都可以参与的公共聊天室',
    users: {},
    messages: [],
    createdAt: new Date().toISOString()
  }
};

// Socket.IO 连接处理
io.on('connection', (socket) => {
  console.log('新用户连接:', socket.id);

  // 用户加入
  socket.on('user_join', async ({ username, userId, room = 'public' }) => {
    users[socket.id] = { username, userId, room };

    // 离开之前的房间
    Object.keys(rooms).forEach(roomId => {
      if (rooms[roomId].users[socket.id]) {
        delete rooms[roomId].users[socket.id];
        socket.leave(roomId);
      }
    });

    // 加入新房间
    socket.join(room);
    if (!rooms[room]) {
      rooms[room] = {
        id: room,
        name: room,
        description: '',
        users: {},
        messages: [],
        createdAt: new Date().toISOString()
      };
    }

    rooms[room].users[socket.id] = { username, userId };

    // 通知房间内用户有新用户加入
    io.to(room).emit('user_joined', {
      username,
      userId,
      room,
      users: Object.values(rooms[room].users),
      messages: rooms[room].messages.slice(-50) // 发送最近的50条消息
    });
  });

  // 群聊消息
  socket.on('group_message', async ({ message, room = 'public' }) => {
    if (!users[socket.id]) return;

    const messageData = {
      id: Date.now(),
      userId: users[socket.id].userId,
      username: users[socket.id].username,
      message,
      timestamp: new Date().toISOString(),
      type: 'group'
    };

    // 保存消息到内存
    if (rooms[room]) {
      rooms[room].messages.push(messageData);
      // 限制消息历史记录数量
      if (rooms[room].messages.length > 500) {
        rooms[room].messages.shift();
      }
    }

    // 保存消息到数据库
    db.saveMessage({
      sender_id: users[socket.id].userId,
      receiver_id: null,  // 群聊无特定接收者
      room_id: room,
      content: message,
      is_group: true,
      created_at: messageData.timestamp
    });

    // 广播消息给房间内所有用户
    io.to(room).emit('group_message', messageData);
  });

  // 私聊消息
  socket.on('private_message', ({ to, message }) => {
    if (!users[socket.id]) return;

    const toSocketId = Object.keys(users).find(id => users[id].userId === to);
    if (!toSocketId) return;

    const messageData = {
      id: Date.now(),
      userId: users[socket.id].userId,
      username: users[socket.id].username,
      message,
      timestamp: new Date().toISOString(),
      type: 'private'
    };

    // 保存消息到数据库
    db.saveMessage({
      sender_id: users[socket.id].userId,
      receiver_id: to,
      room_id: null,
      content: message,
      is_group: false,
      created_at: messageData.timestamp
    });

    // 发送给接收者
    socket.to(toSocketId).emit('private_message', {
      ...messageData,
      from: users[socket.id].userId
    });

    // 发送给发送者自己
    socket.emit('private_message', {
      ...messageData,
      to: to
    });
  });

  // 文件传输
  socket.on('file_message', ({ to, fileId, fileName, fileType, isGroup }) => {
    if (!users[socket.id]) return;

    const messageData = {
      id: Date.now(),
      userId: users[socket.id].userId,
      username: users[socket.id].username,
      fileId,
      fileName,
      fileType,
      timestamp: new Date().toISOString(),
      type: 'file'
    };

    if (isGroup) {
      // 群组文件消息
      const room = to || 'public';
      if (rooms[room]) {
        rooms[room].messages.push(messageData);
      }
      io.to(room).emit('file_message', messageData);
    } else {
      // 私人文件消息
      const toSocketId = Object.keys(users).find(id => users[id].userId === to);
      if (toSocketId) {
        socket.to(toSocketId).emit('file_message', {
          ...messageData,
          from: users[socket.id].userId
        });
      }
      socket.emit('file_message', {
        ...messageData,
        to: to
      });
    }
  });

  // 断开连接
  socket.on('disconnect', () => {
    console.log('用户断开连接:', socket.id);
    if (users[socket.id]) {
      const { username, userId } = users[socket.id];

      // 从所有房间中移除用户
      Object.keys(rooms).forEach(room => {
        if (rooms[room].users[socket.id]) {
          delete rooms[room].users[socket.id];
          io.to(room).emit('user_left', { username, userId });
        }
      });

      // 从用户列表中删除
      delete users[socket.id];
    }
  });
});

// 启动服务器
const PORT = process.env.PORT || 3000;
server.listen(PORT, () => {
  console.log(`服务器运行在端口 ${PORT}`);
});

module.exports = server; 